﻿using Microsoft.Owin.Security;
using System.Collections.Generic;
using System.Threading;

namespace Sustainalytics.LongRunningTaskManager.Interface
{
    /// <summary>
    /// Task context.
    /// </summary>
    public class LongRunningTaskContext : IEqualityComparer<LongRunningTaskContext>
    {
        private readonly ILongRunningTaskInstance _taskInstance;


        /// <summary>
        /// Task title.
        /// </summary>
        public string Title
        {
            get
            {
                return _taskInstance.Status.Title;
            }
            set
            {
                _taskInstance.Status.Title = value;
            }
        }

        /// <summary>
        /// Security token.
        /// </summary>
        public AuthenticationTicket Ticket { get; private set; }

        /// <summary>
        /// Parameter (JSON) passed as argument at task startup.
        /// </summary>
        public string ParamJson { get; private set; }

        /// <summary>
        /// Task status.
        /// </summary>
        public LongRunningTaskStatus TaskStatus
        {
            get
            {
                return this._taskInstance.Status.TaskStatus;
            }
        }

        /// <summary>
        /// Cancellation token used to control cancellation of any task created by the associated task.
        /// </summary>
        public CancellationToken CancellationToken { get; private set; }


        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="taskInstance"></param>
        /// <param name="ticket"></param>
        /// <param name="paramJson"></param>
        /// <param name="taskStatus"></param>
        /// <param name="cancellationToken"></param>
        public LongRunningTaskContext(
            ILongRunningTaskInstance taskInstance,
            AuthenticationTicket ticket,
            string paramJson,
            CancellationToken cancellationToken)
        {
            this._taskInstance = taskInstance;
            this.Ticket = ticket;
            this.ParamJson = paramJson;
            this.CancellationToken = cancellationToken;
        }

        public bool Equals(LongRunningTaskContext x, LongRunningTaskContext y)
        {
            if (x == null && y == null)
                return true;

            if (x == null || y == null)
                return false;

            return ((x.Ticket == null && y.Ticket == null) || x.Ticket == y.Ticket)
                && ((x.ParamJson == null && y.ParamJson == null) || x.ParamJson == y.ParamJson)
                && ((x.TaskStatus == null && y.TaskStatus == null) || new LongRunningTaskStatus().Equals(x.TaskStatus, y.TaskStatus))
                && ((x.CancellationToken == null && y.CancellationToken == null) || x.CancellationToken == y.CancellationToken);
        }

        public int GetHashCode(LongRunningTaskContext obj)
        {
            return 0;
        }
    }
}
